const express = require("express");
const router = express.Router();
const {
  permissionModel,
  roleModel,
  user,
  room,
  dong,
  pay,
  paylist,
  houserent,
} = require("../models/model");
const jwt = require("jsonwebtoken");
const crypto = require("crypto");
const { pipeline } = require("stream");
var path = require("path");
const multer = require("multer");
// 密码加密函数
function md5Password(password) {
  const md5 = crypto.createHash("md5");
  return md5.update(password).digest("hex");
}

// 添加用户
router.post("/userHt", async (req, res) => {
  const { username, password, role } = req.body;
  await user.create({
    username,
    password: md5Password(password),
    role,
  });
  res.send({
    code: 200,
  });
});

// 登录
let tokens = {};
router.post("/login", async (req, res) => {
  const { username, password } = req.body;
  // console.log(username,password)
  const user1 = await user.findOne({
    username,
    password: md5Password(password),
  });
  if (user1) {
    let token = jwt.sign({ username: username }, "2401a", { expiresIn: "1h" });
    tokens[token] = username;
    res.send({
      code: 200,
      token,
      result: user1,
    });
  } else {
    res.send({
      code: 401,
      msg: "用户名或密码错误",
      result: user1,
    });
  }
});

router.get("/menus", async (req, res) => {
  let token = req.headers.authorization;
  // 根据用户名tokens[token]查询对应用户
  let user1 = await user.findOne({ username: tokens[token] });
  // 用户-->角色
  let roleInfo = await roleModel.findOne({ _id: user1.role });
  // 权限id数组-->权限详情
  let permissions = await permissionModel.find({
    _id: { $in: roleInfo.permission },
  });
  // 递归整理权限
  let permission_list = convert(permissions);
  res.send({
    avatar: user1.avatar,
    code: 200,
    rolename: roleInfo.name, //角色名
    username: user1.username, //用户名
    permission_list: permission_list, //权限列表
  });
});

// 递归整理权限列表
function convert(data) {
  function tree(id) {
    let arr = [];
    let filter_data = data.filter((item) => {
      return String(item.parentid) == String(id);
    });

    filter_data.forEach((item) => {
      let obj = {
        _id: item._id,
        name: item.name,
        router_name: item.router_name,
        icon: item.icon,
      };
      children = tree(item._id);
      if (children.length > 0) {
        obj.children = children;
      }
      arr.push(obj);
    });
    return arr;
  }
  return tree(undefined);
}

// 获取所有权限
router.get("/permission", async (req, res) => {
  try {
    let data = await permissionModel.aggregate([
      {
        $match: { parentid: "" }, //用于过滤文档，仅允许满足指定条件的文档进入下一个管道阶段。过滤得到根权限
      },
      {
        $lookup: {
          //于执行左外连接，将当前集合中的文档与另一个集合中的文档进行关联。
          from: "permissions",
          localField: "_id",
          foreignField: "parentid",
          as: "children",
          pipeline: [
            {
              $lookup: {
                from: "permissions",
                localField: "_id",
                foreignField: "parentid",
                as: "children",
              },
            },
            {
              $project: {
                //用于重新构造文档的结构，可以选择性地包含、排除或添加字段。还可以对字段进行重命名、计算新字段等。
                _id: 1,
                name: 1,
                router_name: 1,
                level: 1,
                children: {
                  $cond: {
                    if: { $size: "$children" },
                    then: "$children",
                    else: false,
                  },
                },
              },
            },
            {
              $project: {
                //用于重新构造文档的结构，可以选择性地包含、排除或添加字段。还可以对字段进行重命名、计算新字段等。
                _id: 1,
                name: 1,
                router_name: 1,
                parentid: 1,
                level: 1,
                children: {
                  $cond: {
                    if: { $size: "$children" },
                    then: "$children",
                    else: false,
                  },
                },
              },
            },
          ],
        },
      },
    ]);

    // console.log(data)
    res.send({
      code: 200,
      data: data,
    });
  } catch (error) {
    console.log(error);
    res.status(500).send({
      code: 500,
      message: "服务器错误",
    });
  }
});

// 获取所有角色
router.get("/role", async (req, res) => {
  let data = await roleModel.aggregate([
    {
      $project: {
        _id: 1,
        name: 1,
      },
    },
  ]);
  res.send({
    code: 200,
    data: data,
  });
});

// 添加角色
router.post("/role", async (req, res) => {
  await roleModel.create(req.body);
  res.send({
    code: 200,
  });
});

// 账单列表
// 获取收费类型
router.get("/pay", async (req, res) => {
  let data = await pay.find();
  res.send({
    code: 200,
    data: data,
  });
});

// 获取账单列表
router.get("/paylist", async (req, res) => {
  let data = await paylist.aggregate([
    {
      $lookup: {
        from: "pay",
        localField: "cid",
        foreignField: "_id",
        as: "PData",
      },
    },
    {
      $unwind: "$PData",
    },
    {
      $lookup: {
        from: "user",
        localField: "userid",
        foreignField: "_id",
        as: "UData",
      },
    },
    {
      $unwind: "$UData",
    },
    {
      $lookup: {
        from: "room",
        localField: "rommid",
        foreignField: "_id",
        as: "RData",
      },
    },
    {
      $unwind: "$RData",
    },
    {
      $project: {
        _id: 1,
        cid: "$PData._id",
        cname: "$PData.name",
        cprice: "$PData.price",
        computer: "$PData.computer",
        roomid: "$RData._id",
        roomname: "$RData.name",
        dongid: "$RData.cid",
        userid: "$UData._id",
        username: "$UData.name",
        time: 1,
        status: 1,
        title: 1,
        payable: 1,
      },
    },
  ]);
  res.send({
    code: 200,
    data: data,
  });
});

// 获取楼信息表
router.get("/dong", async (req, res) => {
  let data = await dong.find();
  res.send({
    code: 200,
    data: data,
  });
});

// 获取房间表
router.get("/room", async (req, res) => {
  let data = await room.aggregate([
    {
      $lookup: {
        from: "dong",
        localField: "cid",
        foreignField: "_id",
        as: "DData",
      },
    },
    {
      $unwind: "$DData",
    },
    {
      $project: {
        _id: 1,
        name: 1,
        cid: "$DData._id",
        cname: "$DData.name",
      },
    },
  ]);
  res.send({
    code: 200,
    data: data,
  });
});

// 新建账单
router.post("/bill", async (req, res) => {
  let room1 = await room.findOne({
    _id: req.body.roomid,
  });

  let dong1 = await dong.findOne({
    _id: room1.cid,
  });

  let pay1 = await pay.findOne({
    _id: req.body.cid,
  });

  await paylist.create({
    rommid: req.body.roomid,
    cid: req.body.cid,
    userid: room1.userid,
    time: req.body.time,
    status: false,
    title: req.body.title,
    payable: dong1.s * pay1.price * 12 + 60,
  });
  res.send({
    code: 200,
  });
});

// 删除单条账单
router.delete("/paylist", async (req, res) => {
  await paylist.deleteOne({
    _id: req.query.id,
  });
  res.send({
    code: 200,
  });
});

// 房屋租赁表
router.get("/houserent", async (req, res) => {
  let data = await houserent.aggregate([
    {
      $lookup: {
        from: "room",
        localField: "roomid",
        foreignField: "_id",
        as: "roomData",
      },
    },
    {
      $unwind: "$roomData",
    },
    {
      $lookup: {
        from: "user",
        localField: "roomData.userid",
        foreignField: "_id",
        as: "userData",
      },
    },
    {
      $unwind: "$userData",
    },
    {
      $lookup: {
        from: "dong",
        localField: "roomData.cid",
        foreignField: "_id",
        as: "dongData",
      },
    },
    {
      $project: {
        cate: 1,
        title: 1,
        area: 1,
        desc: 1,
        facility: 1,
        img: 1,
        time: 1,
        _id: 1,
        price: 1,
        uname: "$userData.username",
        tel: "$userData.phone",
        roomname: "$roomData.name",
        dongname: "$dongData.name",
        dongid: "$dongData._id",
        s: "$dongData.s",
      },
    },
  ]);
  res.send({
    code: 200,
    data: data,
  });
});

// 删除房屋租赁信息
router.delete("/houserent", async (req, res) => {
  await houserent.deleteOne({ _id: req.query.id });
  res.send({
    code: 200,
  });
});

// 新增房屋租赁信息
router.post("/houserent", async (req, res) => {
  let { roomid, title, price, cate, facility, desc, time, img } = req.body;
  let room2 = await room.findOne({ _id: req.body.roomid });
  let dong1 = await dong.findOne({ _id: room2.cid });

  await houserent.create({
    cate,
    title,
    price,
    area: dong1.s,
    desc,
    facility,
    time,
    roomid,
    userid: room2.userid,
    img: img,
  });
  res.send({
    code: 200,
  });
});

// 图片上传
// 设置存储配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/"); // 保存文件的目录
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname)); // 使用时间戳和文件扩展名作为文件名
  },
});

// 初始化 multer 实例
const upload = multer({ storage: storage });

// 路由处理文件上传
router.post("/upload", upload.single("file"), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).send("No file uploaded.");
    }
    res.send("http://127.0.0.1:3000/" + req.file.filename);
  } catch (error) {
    res.status(500).send("Error uploading file: " + error.message);
  }
});

module.exports = router;
